//
//  BLEModel.m
//  Test
//
//  Created by SL on 14-7-29.
//  Copyright (c) 2014年 Sheng Long. All rights reserved.
//

#import "BLEModel.h"

#define DATA_HEAD_1     100
#define DATA_HEAD_2     149

//用户指令
#define DATA_ZL_02              2           //02指令，需输入用户信息
#define DATA_ZL_02_NUMBER      12           //发送02指令的位数

#define DATA_ZL_07              7           //07指令，接收信息

#define DATA_ZL_09              9           //09指令，体重清零
#define DATA_ZL_09_NUMBER       1           //发送09指令的位数

#define applicationEnteredBackgroundNotification @"applicationEnteredBackgroundNotification"
#define applicationEnteredForegroundNotification @"applicationEnteredBackgroundNotification"

//已连接设备
#define ALREADY_CONNECTION_DEVICE       @"APP_ALREADY_CONNECTION_DEVICE"

@interface BLEModel()

@property (nonatomic,retain) CBPeripheral *blePeripheral;
@property (nonatomic,retain) NSMutableData *receiveData;
@end

@implementation BLEModel

@synthesize bleManager;
@synthesize blePeripheral;
@synthesize receiveData;
@synthesize bluetoothManager;
@synthesize isManual;

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

-(id)init
{
    self = [super init];
    if (self) {
        
        self.receiveData = [NSMutableData data];
        
        bleManager = [[BLElib alloc]init];
        [bleManager setBLEDelegate:(id)self];
        //        [bleManager startScanningForUUIDString:nil];
        //        [bleManager cleanApplicationIconBadgeNumber];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackgroundNotification:) name:applicationEnteredBackgroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterForegroundNotification:) name:applicationEnteredForegroundNotification object:nil];
    }
    return self;
}

- (void)didEnterBackgroundNotification:(NSNotification*)notification
{
    [bleManager enterBackground];
}

- (void)didEnterForegroundNotification:(NSNotification*)notification
{
    [bleManager enterForeground];
    //    [bleManager cleanApplicationIconBadgeNumber];
}

-(NSString*)getPeripheralID:(CBPeripheral*)peripheral
{
    NSString *current = nil;
    if (CURRENT_VERSION_SEVEN) {
        current = [NSString stringWithFormat:@"%@",peripheral.identifier];
    }else{
        current = [NSString stringWithFormat:@"%@",peripheral.UUID];
    }
    current = [[current componentsSeparatedByString:@" "] lastObject];
    return current;
}

#pragma mark - BLE Delegate
//查找设备
- (void) didFoundPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    if ([self.bleManager isConnected] == NO) {
        
        if (isManual) {
            //手动显示搜索设备
            NSMutableArray *array = [NSMutableArray arrayWithArray:self.bluetoothManager.peripheralArray];
            for (CBPeripheral *p in array) {
                if (CURRENT_VERSION_SEVEN) {
                    if (peripheral.identifier == p.identifier) {
                        return;
                    }
                }else{
                    if (peripheral.UUID == p.UUID) {
                        return;
                    }
                }
            }
            [array addObject:peripheral];
            self.bluetoothManager.peripheralArray = array;
        }else{
            //自动连接已有设备
            NSArray *alreadyArray = [[APP_USERDEFAULTS valueForKeyPath:ALREADY_CONNECTION_DEVICE] componentsSeparatedByString:@";"];
            for (NSString *text in alreadyArray) {
                NSString *current = [self getPeripheralID:peripheral];
                if ([text isEqualToString:current]) {
                    if (![peripheral isConnected]) {
                        assert(peripheral != nil);
                        self.blePeripheral = peripheral;
                        [self.bleManager connectPeripheral:peripheral];
                        break;
                    }
                }
            }
        }
    }
    
    //    if ([peripheral.name isEqualToString:@"BF4030"]) {
    //
    //        if ([bleManager isConnected] == YES) {
    //            return;//if connected, do nothing;
    //        }
    //
    //        if (![peripheral isConnected]) {
    //            assert(peripheral != nil);
    //            self.blePeripheral = peripheral;
    //            [bleManager connectPeripheral:peripheral];
    //        }
    //    }
}

//连接设备
- (void) didConnectPeripheral:(CBPeripheral *)peripheral
{
    CLog(@"连接上设备%@",peripheral.name);
    [[NSNotificationCenter defaultCenter ] postNotificationName:BLUETOOTHMANAGER_LJSBCG object:nil userInfo:@{@"name": peripheral.name}];
    if (isManual) {
        [LoadingFrameView autoDisappearTipview:@"连接成功"];
        isManual = NO;
    }
    //    //
    //    [self.bluetoothManager closeView];
}

//连接设备错误
- (void) didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    if (isManual) {
        [LoadingFrameView autoDisappearTipview:@"连接失败"];
        isManual = NO;
    }
    //    bleManager = [bleManager init];
    //    [bleManager startScanningForUUIDString:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:BLUETOOTHMANAGER_LJSBSB object:nil];
}

//断开设备
- (void) didDisconnectPeripheral:(CBPeripheral *)peripheral
{
    CLog(@"name====%@",peripheral.name);
    if (isManual) {
        [LoadingFrameView autoDisappearTipview:@"设备断开连接"];
        isManual = NO;
    }
    //    bleManager = [bleManager init];
    //    [LoadingFrameView autoDisappearTipview:@"连接失败"];
    //    [bleManager startScanningForUUIDString:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:BLUETOOTHMANAGER_LJSBSB object:nil];
}

//接收设备数据
- (void) didRecieveData:(NSData *)data
{
    CLog(@"接收设备数据====%@",data);
    if (data) {
        [self.receiveData appendData:data];
        [self jyData];
    }
}

//发送数据返回
- (void) didSendData:(NSData *)data
{
    CLog(@"data===发送数据返回====%@",data);
}

#pragma mark - 用户信息
-(void)sendUserMsg
{
    NSMutableArray *alreadyArray = [NSMutableArray arrayWithArray:[[APP_USERDEFAULTS valueForKeyPath:ALREADY_CONNECTION_DEVICE] componentsSeparatedByString:@";"]];
    BOOL have = NO;
    for (NSString *text in alreadyArray) {
        NSString *current = [self getPeripheralID:bleManager.connectedPeripheral];
        if ([text isEqualToString:current]) {
            have = YES;
            break;
        }
    }
    if (!have) {
        //存储已连接设备
        NSString *current = [self getPeripheralID:bleManager.connectedPeripheral];
        [alreadyArray addObject:current];
        [APP_USERDEFAULTS setValue:[alreadyArray componentsJoinedByString:@";"] forKeyPath:ALREADY_CONNECTION_DEVICE];
        CLog(@"%@",[APP_USERDEFAULTS valueForKeyPath:ALREADY_CONNECTION_DEVICE]);
    }
    
    
    
    //发送用户信息
    NSMutableData *data1 = [NSMutableData dataWithData:[self getdata:[NSString stringWithFormat:@"%d",DATA_HEAD_1]]];
    [data1 appendData:[self getdata:[NSString stringWithFormat:@"%d",DATA_HEAD_2]]];
    [data1 appendData:[self getdata:[NSString stringWithFormat:@"%d",DATA_ZL_02_NUMBER]]];
    [data1 appendData:[self getdata:[NSString stringWithFormat:@"%d",DATA_ZL_02]]];
    //用户编号：8字节字符串。
    [data1 appendData:[self ddMsg:[self addDataNumber:8 data:[self getdata:APP_USER_MSG.id]]]];
    //用户身高：1字节，uint8_t类型，单位为厘米。
    [data1 appendData:[self getdata:APP_USER_MSG.height]];
    //用户性别：1字节，
    //00：男性
    //01：女性，孕早期或孕前或产后（孕<12周）。
    //02：女性，孕中期（孕13～27周）。
    //其他：女性，孕晚期（孕28周～分娩）
    NSString *state = @"0";
    switch ([APP_USER_MSG.pregnancy intValue]) {
        case 2:
        {
            NSDate *date = [z_DateTime dencodeTime:APP_USER_MSG.last_menstrual format:APP_SELECTPICKERVIEW_DATE_FORMAT];
            int day = [[NSDate date] timeIntervalSinceDate:date]/(24*2600);
            if (day<=12*7) {
                state = @"1";
            }else if (day<=27*7){
                state = @"2";
            }else if(day<360){
                state = @"3";
            }
        }
            break;
        default:
        {
            //孕前和产后
            state = @"1";
        }
            break;
    }
    [data1 appendData:[self getdata:state]];
    
    //用户年龄：1字节，uint8_t类型。
    float nn = [[NSDate date] timeIntervalSinceDate:[z_DateTime dencodeTime:APP_USER_MSG.birthday format:APP_SELECTPICKERVIEW_DATE_FORMAT]]/(24*3600*365);
    int nnint = (int)nn;
    [data1 appendData:[self getdata:[NSString stringWithFormat:@"%d",(nn>nnint?nnint+1:nnint)]]];
    [data1 appendData:[self getYHResult:data1]];
    [bleManager sendData:data1];
}

//体重清零
-(void)cleanUserMsg
{
    //体重清零
    NSMutableData *data1 = [NSMutableData dataWithData:[self getdata:[NSString stringWithFormat:@"%d",DATA_HEAD_1]]];
    [data1 appendData:[self getdata:[NSString stringWithFormat:@"%d",DATA_HEAD_2]]];
    [data1 appendData:[self getdata:[NSString stringWithFormat:@"%d",DATA_ZL_09_NUMBER]]];
    [data1 appendData:[self getdata:[NSString stringWithFormat:@"%d",DATA_ZL_09]]];
    [data1 appendData:[self getYHResult:data1]];
    [bleManager sendData:data1];
}

-(void)getUserMsg
{
    //接收的信息====<64952e07 004c0000 00000000 007705a6 4230f7a9 c160c0cc c15e9096 42f34c88 418689e8 42f4dda9 4180b6f7 4006e7d6 44fa>

    //每次读取字节数
    int total = 4;
    
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:1];
    for (int i = 0; i < 9; i++) {
        float zhi = [self getFloat:[self ddMsg:[self getData:receiveData index:(13+total*i) end:total]]];
        [array addObject:[NSString stringWithFormat:@"%.2f",zhi]];
        CLog(@"获取到的值是====%f",zhi);
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:BLUETOOTHMANAGER_JSSBSJ object:nil userInfo:@{@"data": array}];
}

#pragma mark - 自定义方法
//校验数据
-(void)jyData
{
    //
    Byte *byte = (Byte *)[receiveData bytes];
    if (receiveData.length>=4) {
        //包含包头和数据长度
        if (byte[0] == DATA_HEAD_1 && byte[1] == DATA_HEAD_2) {
            //正常数据
            //获取指令
            int zl = byte[3];
            if (zl == DATA_ZL_02) {
                //发送用户信息
                if ([self getDataSucess]) {
                    [self sendUserMsg];
                    [self.receiveData setLength:0];
                }
            }else if (zl == DATA_ZL_07){
                //接收信息
                if ([self getDataSucess]) {
                    [self getUserMsg];
                    [self.receiveData setLength:0];
//                    [self cleanUserMsg];
                }
            }
        }else{
            //清空数据
            [self.receiveData setLength:0];
        }
    }else{
        if (receiveData.length == 1 && byte[0] != DATA_HEAD_1) {
            [self.receiveData setLength:0];
        }else if ((receiveData.length == 2 || receiveData.length == 3) && (byte[0] != DATA_HEAD_1 || byte[1] != DATA_HEAD_2)){
            [self.receiveData setLength:0];
        }
    }
}

//校验数据是否获取成功
-(BOOL)getDataSucess
{
    Byte *byte = (Byte *)[receiveData bytes];
    if (receiveData.length>3) {
        //获取数据长度
        int length = byte[2];
        //数据长度+2个字节包头+1个长度字节+1个指令字节
        if (receiveData.length >= (length+2+1+1)) {
            //获取数据成功
            NSData *data1 = [self getData:receiveData index:0 end:length+2+1];
            NSData *data2 = [self getData:receiveData index:length+2+1 end:1];
            if ([[self getYHResult:data1] isEqualToData:data2]) {
                //数据校验成功
                CLog(@"接收的信息====%@",receiveData);
                return YES;
            }else{
                //校验失败
                //清空数据
                [self.receiveData setLength:0];
                return NO;
            }
        }
    }
    return NO;
}

//获取    data数据流    index   位置后面    end位数   字节流
-(NSData*)getData:(NSData*)data index:(int)index end:(int)end
{
    Byte *byte = (Byte *)[data bytes];
    
    NSMutableData *newData = [NSMutableData dataWithCapacity:1];
    for (int i = index; i < (end+index); i++) {
        int c = byte[i];
        [newData appendData:[self getdata:[NSString stringWithFormat:@"%d",c]]];
    }
    
    return newData;
}

//获取异或值
-(NSData*)getYHResult:(NSData*)data
{
    //
    Byte *byte = (Byte *)[data bytes];
    int c = byte[0];
    for (int i = 1; i < data.length; i++) {
        c = c ^ byte[i];
    }
    return [self getdata:[NSString stringWithFormat:@"%d",c]];
}

//转换16进制流
-(NSData*)getdata:(NSString*)old
{
    Byte bb1=[old intValue];
    NSData *dd1 = [[NSData alloc] initWithBytes:&bb1 length:sizeof(bb1)];
    return dd1;
}

//补齐位数
-(NSData*)addDataNumber:(NSInteger)number data:(NSData*)data
{
    NSInteger total = number - data.length;
    NSMutableData *newData = [NSMutableData dataWithData:data];
    for (int i = 0 ; i < total; i++) {
        NSMutableData *d = [NSMutableData dataWithData:[self getdata:@"0"]];
        [d appendData:newData];
        newData = d;
        //        [newData appendData:d];
    }
    return newData;
}

//小端模式，颠倒信息
-(NSData*)ddMsg:(NSData*)oldData
{
    NSMutableData *data = [NSMutableData dataWithCapacity:1];
    
    Byte *byte = (Byte *)[oldData bytes];
    for (int i = (int)oldData.length-1; i >= 0; i--) {
        int c = byte[i];
        [data appendData:[self getdata:[NSString stringWithFormat:@"%d",c]]];
    }
    return data;
}

//nsdata转换成float
-(float)getFloat:(NSData*)data
{
    Byte *tbytes = (Byte*)[data bytes];
    int bint = 0;
    for (int i = 0; i < [data length]; i++) {
        bint += ((tbytes[i]&0xff)<<(8*([data length]-1-i)));
    }
    float bfloat = *(float*)&bint;
    return bfloat;
    
    //    int a;
    //    [data getBytes:&a length:sizeof(a)];
    //    float aaa = *(float *)&a;
    //    return aaa;
    
    //    float ff = 16;
    //    int ii = *(int*)&ff;
    //    CLog(@"x==%x",ii);
}

//将NSString转换成对应字符的NSData
-(NSData*)stringChangeData:(NSString*)text
{
    ///// 将16进制数据转化成Byte 数组
    NSString *hexString = text; //16进制字符串
    int j=0;
    Byte bytes[hexString.length/2];
    ///3ds key的Byte 数组， 128位
    for(int i=0;i<[hexString length];i++)
    {
        int int_ch; /// 两位16进制数转化后的10进制数
        
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        int int_ch1;
        if(hex_char1 >= '0' && hex_char1 <='9')
            int_ch1 = (hex_char1-48)*16; //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        else
            int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97
        i++;
        
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        int int_ch2;
        if(hex_char2 >= '0' && hex_char2 <='9')
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch2 = hex_char2-55; //// A 的Ascll - 65
        else
            int_ch2 = hex_char2-87; //// a 的Ascll - 97
        
        int_ch = int_ch1+int_ch2;
        NSLog(@"int_ch=%d",int_ch);
        bytes[j] = int_ch; ///将转化后的数放入Byte数组里
        j++;
    }
    NSData *newData = [[NSData alloc] initWithBytes:bytes length:hexString.length/2];
    
    return newData;
}


@end
